import { DatePicker, Input, InputNumber } from '@/components/AntdProxy';
import CommonDrawer from '@/components/CommonDrawer';
import { CrudFormLayout } from '@/components/Crud';
import { DriverSelect, VehicleSelect } from '@/components/CustomForm';
import ImageUpload from '@/components/ImageUpload';
import { REQUIRED } from '@/constants/rules';
import request from '@/utils/request';
import { useAsyncEffect } from 'ahooks';
import { Form, message } from 'antd';
import dayjs from 'dayjs';
import styles from './index.less';

const Save = (props) => {
  const { open, record, onCancel, onOk } = props;
  const [form] = Form.useForm();

  useAsyncEffect(() => {
    if (record) {
      const formData = {
        ...record,
        beginTime: dayjs(record.beginTime),
        endTime: dayjs(record.endTime),
        images: record.images ? [{ url: record.images }] : [],
      };
      form?.setFieldsValue(formData);
    }
  }, [record]);

  const handleOk = async () => {
    const values = await form.validateFields();
    const url = record ? '/datas/etc/price/update' : '/datas/etc/price/add';
    const params = {
      ...values,
      beginTime: values.beginTime.format('YYYY-MM-DD HH:mm:ss'),
      endTime: values.endTime.format('YYYY-MM-DD HH:mm:ss'),
    };
    if (values.images && values.images.length) {
      params.images = values.images[0].url;
    } else {
      params.transferLogs = '';
    }
    if (record) {
      params.etcPriceId = record?.etcPriceId;
    }
    await request({
      url,
      method: 'POST',
      data: params,
    });
    message.success('操作成功');
    onOk?.();
  };

  return (
    <CommonDrawer
      title={record ? '更新ETC费用信息' : '新建ETC费用信息'}
      open={true}
      onClose={onCancel}
      onOk={handleOk}
      afterOpenChange={(visible) => {
        if (!visible) {
          form.resetFields();
        }
      }}
      width={1000}
      destroyOnHidden
    >
      <Form form={form} layout="vertical" style={{ height: '100%' }}>
        <div className={styles.container}>
          <div className={styles.left}>
            <Form.Item label="图片" name="images">
              <ImageUpload maxCount={1} />
            </Form.Item>
          </div>
          <div className={styles.right}>
            <CrudFormLayout itemMinWidth={180}>
              <Form.Item label="车辆" name="vehicleId" rules={[REQUIRED]}>
                <VehicleSelect
                  placeholder="请选择车辆"
                  onChange={(val, option) => {
                    try {
                      const driver = JSON.parse(option.drivers)?.[0];
                      if (driver) {
                        form.setFieldsValue({
                          driverId: driver?.driverId,
                          realname: driver?.realname,
                        });
                      }
                    } catch (error) {}
                  }}
                />
              </Form.Item>
              <Form.Item label="司机" name="driverId">
                <DriverSelect placeholder="请选择司机" />
              </Form.Item>
              <Form.Item label="费用（元）" name="price">
                <InputNumber placeholder="请输入费用" />
              </Form.Item>
              <Form.Item label="开始时间" name="beginTime">
                <DatePicker
                  needConfirm={false}
                  placeholder="请选择开始时间"
                  showTime
                />
              </Form.Item>
              <Form.Item label="结束时间" name="endTime">
                <DatePicker
                  needConfirm={false}
                  placeholder="请选择结束时间"
                  showTime
                />
              </Form.Item>
              <Form.Item label="进入站点" name="beginStation">
                <Input placeholder="请输入进入站点名称" />
              </Form.Item>
              <Form.Item label="离开站点" name="endStation">
                <Input placeholder="请输入离开站点名称" />
              </Form.Item>
            </CrudFormLayout>
            <Form.Item label="备注" name="remark">
              <Input.TextArea placeholder="请输入备注" />
            </Form.Item>
          </div>
        </div>
      </Form>
    </CommonDrawer>
  );
};

export default Save;
